<template>
    <div>
        <el-button type="primary" icon="delete" class="handle-del mr10" @click="addSelfImage">+ 导入镜像</el-button>
        <el-table
            v-loading="loading"
            :data="tableData"
            style="width: 100%">
            <el-table-column
                label="镜像名"
                width="200">
                <template slot-scope="scope">
                    <el-popover >
                        <div slot="reference" class="name-wrapper">
                            <el-tag size="medium">{{ scope.row.fullName }}</el-tag>
                        </div>
                    </el-popover>
                </template>
            </el-table-column>
            <el-table-column
                label="介绍"
                width="180">
                <template slot-scope="scope">
                    <el-popover >
                        <div slot="reference" class="name-wrapper">
                            {{ scope.row.description }}
                        </div>
                    </el-popover>
                </template>
            </el-table-column>
            <el-table-column
                label="使用说明"
                width="230">
                <template slot-scope="scope">
                    <el-popover >
                        <div slot="reference" class="name-wrapper">
                            {{ scope.row.instructions }}
                        </div>
                    </el-popover>
                </template>
            </el-table-column>
            <el-table-column
                label="状态"
                width="100">
                <template slot-scope="scope">
                    <!-- <el-popover > -->
                        <div slot="reference" class="name-wrapper">
                            <el-button
                                size="mini"
                                type="primary"
                                @click="changeState(scope.$index, scope.row)">{{ scope.row.hasOpen }}</el-button>
                        </div>

                    <!-- </el-popover> -->
                </template>
            </el-table-column>
            <el-table-column
                label="镜像大小"
                width="180">
                <template slot-scope="scope">
                    <el-popover >
                        <div slot="reference" class="name-wrapper">
                            {{ scope.row.size }}
                        </div>
                    </el-popover>
                </template>
            </el-table-column>
            <el-table-column
                label="来源"
                width="130">
                <template slot-scope="scope">
                    <el-popover >
                        <div slot="reference" class="name-wrapper">
                            {{ scope.row.authorName }}
                        </div>
                    </el-popover>
                </template>
            </el-table-column>
            <el-table-column label="操作">
                <template slot-scope="scope">
                    <el-button
                        size="mini"
                        @click="getDetails(scope.$index, scope.row)">详情</el-button>
                    <el-button
                        size="mini"
                        type="danger"
                        @click="deleteImage(scope.$index, scope.row)">删除</el-button>
                    <!--todo-->
                </template>
            </el-table-column>
        </el-table>

        <!--分页效果-->
        <div class="fenYe">
            <div class="block">
                <el-pagination
                    @current-change="handleCurrentChange"
                    :page-size="5"
                    layout="prev, pager, next, jumper"
                    :total="listTotal">
                </el-pagination>
            </div>
        </div>

        <!--详情提示框-->
        <el-dialog
            title="详细信息"
            :visible.sync="dialogVisible"
            width="50%"
            :before-close="handleClose">

            <div id="editor" class="json-editor"></div>
            <pre id="json"></pre>

            <span slot="footer" class="dialog-footer">
                <el-button @click="dialogVisible = false">取 消</el-button>
                <el-button type="primary" @click="dialogVisible = false">确 定</el-button>
            </span>
        </el-dialog>

        <!--导入镜像的输入框-->
        <el-dialog
            title="导入镜像"
            :visible.sync="dialogVisible1"
            width="50%"
            :before-close="handleClose1">
            <el-form :model="ruleForm2" status-icon :rules="rules2" ref="ruleForm2" label-position="left" label-width="100px" class="demo-ruleForm" >
                <el-form-item label="镜像名" prop="fullName">
                    <el-input v-model="ruleForm2.fullName" autoComplete="off"></el-input>
                </el-form-item>
                <el-form-item label="镜像介绍" prop="description">
                    <el-input  v-model="ruleForm2.description" autoComplete="off"></el-input>
                </el-form-item>
                <el-form-item label="镜像使用说明" prop="Instructions">
                    <el-input v-model.number="ruleForm2.Instructions"></el-input>
                </el-form-item>

                <el-upload
                    name="file"
                    class="upload-demo"
                    :action="imageAction"
                    :headers="urlHeaders"
                    :data="ruleForm2"
                    :on-preview="handlePreview"
                    :on-remove="handleRemove"
                    :before-remove="beforeRemove"
                    :before-upload="beforeUpload111"
                    :on-success="upLoadSuccess"
                    :on-error="upLoadError"
                    multiple
                    :limit="1"
                    :on-exceed="handleExceed"
                    :file-list="fileList">
                    <el-button size="small" type="primary">点击上传</el-button>
                    <!-- <div slot="tip" class="el-upload__tip">只能上传jpg/png文件，且不超过500kb</div> -->
                </el-upload>

            </el-form>
            <span slot="footer" class="dialog-footer">
                <el-button type="primary" @click="dialogVisible1 = false">完成</el-button>
            </span>
        </el-dialog>

    </div>
</template>

<script>
    import '../../../static/js/jsoneditor'
    import store from '../../vuex/store'
    export default {
        name: "Table-images-private",
        data() {
            //镜像名校验规则
            var validatePass = (rule, value, callback) => {
                for(var i=0;i<value.length;i++) {
                    if (/^[A-Z]+$/.test( value[i] )) {
                        callback(new Error('请不要输入大写英文字母'));
                    }
                }
                if (value === '') {
                    callback(new Error('请输入镜像名'));
                }
                this.getImageFullNameIsOnlyOne(value);
                if (store.state.ImageFullNameIsOnlyOne===0) {
                    callback(new Error('该镜像名已存在'));
                }
                callback();
            };

            return {
                tableData: [],
                dialogVisible:false,
                listTotal:0,
                currentPage:1,
                dialogVisible1:false,

                ruleForm2: {
                    fullName: '',
                    description: '',
                    Instructions: ''
                },

                rules2: {
                    fullName: [
                        { required: true,validator: validatePass, trigger: 'blur' }
                    ],

                },

                fileList: [],
                imageAction:`api/docker/customer/import/newImage`,
                urlHeaders:{
                    'Authorization':`Bearer ${sessionStorage.getItem("Token")}`
                },
                loading:true,

            }
        },
        methods: {

            //上传前的检验
            beforeUpload111() {
                var val =this.ruleForm2.fullName;
                if(val==='') {
                    this.$message.warning("镜像名不能为空");
                    // callback(new Error('请输入镜像名'));
                    return false;
                }
                for(var i=0;i<val.length;i++) {
                    if (/^[A-Z]+$/.test( val[i] )) {
                        // callback(new Error('请不要输入大写英文字母'));
                        this.$message.warning("请不要输入大写英文字母");
                        return false;
                    }
                }
                // if (value === '') {
                //     this.$message.warning('请输入镜像名');
                //     return false;
                // }
                this.getImageFullNameIsOnlyOne(val);
                if (store.state.ImageFullNameIsOnlyOne===0) {
                    // callback(new Error('该镜像名已存在'));
                    this.$message.warning("该镜像名已存在");
                    return false;
                }
            },

            handleRemove(file, fileList) {
                console.log(file, fileList);
            },
            handlePreview(file) {
                console.log(file);
            },
            handleExceed(files, fileList) {
                this.$message.warning(`当前限制选择 1 个文件，本次选择了 ${files.length} 个文件，共选择了 ${files.length + fileList.length} 个文件`);
            },
            beforeRemove(file, fileList) {
                return this.$confirm(`确定移除 ${ file.name }？`);
            },
            upLoadSuccess() {
                this.$message.success("上传成功");
                this.getSelfImages(this.currentPage);
            },
            upLoadError() {
                this.$message.error("上传失败");
            },



            addSelfImage() {
                this.dialogVisible1=true;
            },

            changeState(index,row) {
              this.changeImageState(row.fullName,row.hasOpen);
            },
            getDetails(index, row) {
                console.log(index, row.imageId);
                this.getImageDetails(row.imageId);
            },
            exportImage(index, row) {
                console.log(index, row);
                this.downImage(row.fullName);
            },
            handleClose(done) {
                this.$confirm('确认关闭？')
                    .then(_ => {
                        done();
                    })
                    .catch(_ => {});
            },
            handleClose1(done) {
                this.$confirm('确认关闭？')
                    .then(_ => {
                        done();
                    })
                    .catch(_ => {});
            },
            handleCurrentChange(val) {
                this.getSelfImages(val);
                store.state.SelfImageCurrentPage = val;
            },
            //删除镜像,点击确认后才开始删
            deleteImage(index,row) {
                var state;
                this.$confirm('确认删除？')
                    .then(_ => {


                        var token='Bearer '+sessionStorage.getItem("Token");
                        let config = {
                            headers: {
                                'Authorization':token,
                            }
                        };
                        var url = "/api/docker/customer/remove/theImage"+"?imageId="+row.imageId;
                        this.$axios.get(url,config).then(res=>{
                            console.log(res);
                            if(res.data.code===1) {
                                this.$message.success("成功删除该镜像");
                            } else {
                                this.$message.error("删除该镜像失败1");
                            }
                        }).catch(reason => {
                            console.log(reason);
                            this.$message.error("删除该镜像失败2");
                        })

                    })
                    .catch(_ => {});
            },

            //获取镜像的详细信息
            getImageDetails(imageId) {
                this.dialogVisible=true;

                var token='Bearer '+sessionStorage.getItem("Token");
                let config = {
                    headers: {
                        'Authorization':token,
                    }
                };
                var url = "/api/docker/getDetailAboutImage"+"?imageId="+imageId;
                this.$axios.get(url,config).then(res=>{
                    console.log(res);
                    if(res.data.code===1) {
                        this.$message.success("成功获取镜像详细信息");

                        let json = res.data.data;
                        $('#editor').jsonEditor(json, {
                            change: function () {
                                $('#json').html(JSON.stringify(json));
                            }
                        });

                    } else {
                        this.$message.error("获取镜像详细信息失败1");
                    }
                }).catch(reason => {
                    console.log(reason);
                    this.$message.error("获取镜像详细信息失败2");
                })

            },

            //导出镜像
            downImage(fullName) {
                var token='Bearer '+sessionStorage.getItem("Token");
                let config = {
                    headers: {
                        'Authorization':token,
                    }
                };
                var url = "/api/docker/customer/downImage"+"?fullName="+fullName;
                this.$axios.get(url,config).then(res=>{
                    console.log(res);
                    if(res.data.code===1) {
                        alert("点击确认，开始下载；\n下载比较慢，请耐心等候！");
                        window.open(res.data.data);

                    } else {
                        this.$message.error("获取image的下载地址失败");
                    }
                }).catch(reason => {
                    console.log(reason);
                    this.$message.error("获取image的下载地址失败");
                })
            },

            //根据当前页页码，来获取私人镜像
            getSelfImages(val) {
                // this.currentPage = val;
                var token='Bearer '+sessionStorage.getItem("Token");
                let config = {
                    headers: {
                        'Authorization':token,
                    }
                };
                var url = "/api/docker/user/getSelfUploadImages"+"?pageIndex="+val;
                this.$axios.get(url,config).then(res=>{
                    console.log(res);
                    if(res.data.code===1) {
                        // this.$message.success("成功获取镜像列表");
                        for (var i=0; i< res.data.data.length; i++){
                            if(res.data.data[i].hasOpen ===1) {
                                res.data.data[i].hasOpen ="公开";
                            }else {
                                res.data.data[i].hasOpen ="私有";
                            }
                        }
                        this.tableData=res.data.data;

                        for(var j=0;j<this.tableData.length;j++) {
                            // if (this.tableData[i].size<1024)
                            this.tableData[j].size=this.renderSize(this.tableData[j].size);
                        }


                    } else {
                        this.$message.error("获取私人镜像列表失败");
                    }
                }).catch(reason => {
                    console.log(reason);
                    this.$message.error("获取私人镜像列表失败");
                })
            },

            //初始化时，获取私人镜像
            getFirstSelfImages() {
                var token='Bearer '+sessionStorage.getItem("Token");
                let config = {
                    headers: {
                        'Authorization':token,
                    }
                };
                var url = "/api/docker/user/getSelfUploadImages"+"?pageIndex=1";
                this.$axios.get(url,config).then(res=>{
                    console.log(res);
                    if(res.data.code===1) {
                        this.$message.success("成功获取私人镜像列表");

                        console.log(this.tableData);
                        for (var i=0; i< res.data.data.length; i++){
                            if(res.data.data[i].hasOpen ===1) {
                                res.data.data[i].hasOpen ="公开";
                            }else {
                                res.data.data[i].hasOpen ="私有";
                            }
                        }
                        this.tableData=res.data.data;
                        this.loading=false;
                        for(var j=0;j<this.tableData.length;j++) {
                            // if (this.tableData[i].size<1024)
                            this.tableData[j].size=this.renderSize(this.tableData[j].size);
                        }
                    } else {
                        this.$message.error("获取私人镜像列表失败");
                    }


                }).catch(reason => {
                    console.log(reason);
                    this.$message.error("获取私人镜像列表失败");
                })
            },

            //初始化时，获取私人镜像总数
            getSelfImagesTotal() {
                var token='Bearer '+sessionStorage.getItem("Token");
                let config = {
                    headers: {
                        'Authorization':token,
                    }
                };
                var url = "/api/docker/user/getSelfUploadImagesTotal";
                this.$axios.get(url,config).then(res=>{
                    console.log(res);
                    if(res.data.code===1) {
                        this.$message.success("成功获取私人镜像总数");
                        this.listTotal=res.data.data;

                    } else {
                        this.$message.error("获取私人镜像总数失败");
                    }
                }).catch(reason => {
                    console.log(reason);
                    this.$message.error("获取私人镜像总数失败");
                })
            },

            //改变，镜像的状态
            changeImageState(fullName,state) {
                var token='Bearer '+sessionStorage.getItem("Token");
                let config = {
                    headers: {
                        'Authorization':token,
                    }
                };
                var url = "/api/docker/changeSelfImageState"+"?fullName="+fullName+"&&state="+state;
                this.$axios.get(url,config).then(res=>{
                    console.log(res);
                    if(res.data.code===1) {
                        this.$message.success("成功修改镜像的状态");
                        this.getSelfImages(store.state.SelfImageCurrentPage);
                    } else {
                        this.$message.error("修改镜像的状态失败");
                    }
                }).catch(reason => {
                    console.log(reason);
                    this.$message.error("修改镜像的状态失败");
                })

            },

            //验证，镜像名是否已存在
            getImageFullNameIsOnlyOne(val) {
                var token='Bearer '+sessionStorage.getItem("Token");
                let config = {
                    headers: {
                        'Authorization':token,
                    }
                };
                var url = "/api/docker/getImageFullNameIsOnlyOne"+"?fullName="+val;
                this.$axios.get(url,config).then(res=>{
                    console.log(res);
                    if (res.data.code ===1){
                        this.$message.success("该镜像名还未存在！");
                    } else {
                        alert("该镜像名已存在！");
                    }

                }).catch(reason => {
                    console.log(reason);
                    this.$message.error("确认镜像名信息失败");

                })
            },
            //  格式化文件大小
            renderSize(value) {
                if (null == value || value == '') {
                    return "0 Bytes";
                }
                var unitArr = new Array("Bytes", "KB", "MB", "GB", "TB", "PB", "EB", "ZB", "YB");
                var index = 0,
                    srcsize = parseFloat(value);
                index = Math.floor(Math.log(srcsize) / Math.log(1024));
                var size = srcsize / Math.pow(1024, index);
                //  保留的小数位数
                size = size.toFixed(2);
                return size + unitArr[index];
            },

        },
        created() {
            this.getSelfImagesTotal();
            this.getFirstSelfImages();
        }
    }
</script>

<style scoped>
    .upload-demo{
        text-align: center;
    }
</style>
